/*
 * @Date: 2023-12-18 17:55:55
 * @LastEditors: 玄绮 shijiahansi@qq.com
 * @LastEditTime: 2024-04-13 16:34:47
 * @FilePath: \client\src\forms\mainwindow\listforms\contactform\roomlistform.cpp
 */
#include "roomlistform.h"

#include "CommonUtils.h"
#include "ui_roomlistform.h"

#include <Application.h>
#include <QString>
#include <iostream>
#include <ostream>

RoomListForm::RoomListForm(WindowManager& manager, QWidget* parent) : QWidget(parent),
                                                                      manager(manager),
                                                                      ui(new Ui::RoomListForm) {
    ui->setupUi(this);
    init();
    ui->listWidget->setVerticalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAlwaysOff);
}

RoomListForm::~RoomListForm() {
    delete ui;
}

void RoomListForm::init() {
    auto app = Application::instance();
    connect(app, &Application::signalGetRoomList, this, &RoomListForm::onGetRoomList);
    connect(ui->listWidget, &QListWidget::itemClicked, this, &RoomListForm::onItemClicked);
    connect(ui->listWidget, &QListWidget::itemDoubleClicked, this, &RoomListForm::onItemDoubleClicked);
}

void RoomListForm::addWidget(data::ChatRoomInfo& info) {
    QListWidgetItem* item     = new QListWidgetItem(ui->listWidget);
    UserItem*        userItem = new UserItem(ui->listWidget);

    ui->listWidget->addItem(item);
    ui->listWidget->setItemWidget(item, userItem);
    item->setSizeHint(QSize(172, 74));

    userItem->setUserId(info.roomid().c_str());
    userItem->setSign(info.sign().c_str());
    userItem->setName(info.name().c_str());
    userItem->setPixmap(info.headshot().c_str());
}

void RoomListForm::initChatRoomList() {
    for (auto&& item : m_chatrooms) {
        addWidget(*item.second);
    }
}

void RoomListForm::onGetRoomList(int code) {
    if (!code) {
        auto rooms = Application::instance()->rooms();
        for (auto& i : rooms) {
            m_chatrooms[i->roomid().c_str()] = i;
        }
        initChatRoomList();
    }
}

void RoomListForm::onItemClicked(QListWidgetItem* item) {
}

void RoomListForm::onItemDoubleClicked(QListWidgetItem* item) {
    QWidget*  widget   = ui->listWidget->itemWidget(item);
    UserItem* userItem = static_cast<UserItem*>(widget);

    auto userId = userItem->getUserId();

    qDebug() << "roomId :" << userId;
    auto f = m_chatrooms[userId];
    qDebug() << "roomId :" << f->roomid().c_str();

    auto* chatListForm = manager.getChatListForm();
    if (chatListForm) {
        chatListForm->addNewChat(*f);
    }

    emit signalToggle();
}